//
//  PCDRightDropView.m
//  AresOpenPlatformSDK
//
//  Created by 刘明飞 on 2020/9/16.
//  Copyright © 2020 P&C. All rights reserved.
//

#import "PCDRightDropView.h"

#define kWindow [UIApplication sharedApplication].keyWindow
#define kCellIdentifier @"PCDCellIdentifier"
#define kDropMenuCellID @"PCDDropMenuCellID"
#define kPCDScreenWidth [UIScreen mainScreen].bounds.size.width

#define itemWidth 120
#define itemHeight 40
#define arrowSize 8
#define rightSpace 8

@interface PCDRightDropView()<UITableViewDelegate,UITableViewDataSource>
//蒙版
@property (nonatomic, strong) UIView *cover;
@property (nonatomic, strong) UITableView *tableView;
//存放标题和图片数组
@property (nonatomic, strong) NSMutableArray *titleImageArrM;
@property (nonatomic, assign) CGFloat rowHeight;
//rgb的可变数组
@property (nonatomic, strong) NSMutableArray *RGBStrValueArr;

@end

@implementation PCDRightDropView

- (NSMutableArray *)titleImageArrM {
    if (!_titleImageArrM) {
        _titleImageArrM = [NSMutableArray array];
    }
    return _titleImageArrM;
}

- (NSMutableArray *)RGBStrValueArr {
    if (!_RGBStrValueArr) {
        _RGBStrValueArr = [NSMutableArray array];
    }
    return _RGBStrValueArr;
}

+ (instancetype)showWithTitleArr:(NSArray *)titleArr ImageArr:(NSArray *)imageArr type:(PCDDropType)type handler:(ItemHandler)selectHandler {
	return [[self alloc] initWithTitleArr:titleArr ImageArr:imageArr type:type handler:selectHandler];
}

- (instancetype)initWithTitleArr:(NSArray *)titleArr ImageArr:(NSArray *)imageArr type:(PCDDropType)type handler:(ItemHandler)selectHandler{
	
    
    if (self = [super init]) {
        //初始化赋值
		self.frame = CGRectMake(kPCDScreenWidth-itemWidth-rightSpace, [PCDUtil IsIphoneX]?88:64, itemWidth, itemHeight*titleArr.count + arrowSize);
        _arrowOffset = itemWidth - arrowSize - rightSpace;
        _type = type;
        _rowHeight = itemHeight;
        self.RGBStrValueArr = [NSMutableArray arrayWithObjects:@(255),@(255),@(255), nil];
        _titleColor = [UIColor blackColor];
        _lineColor = [UIColor lightGrayColor];
		self.selectHandler = selectHandler;
        //字典转模型
        for (int i = 0; i < titleArr.count; i++) {
            NSMutableDictionary *tempDict = [NSMutableDictionary dictionary];
            [tempDict setObject:titleArr[i] forKey:@"title"];
            if (imageArr && imageArr.count > 0) {
                  if (i != imageArr.count) {
                      [tempDict setObject:imageArr[i] forKey:@"image"];
                  }
            }
            [tempDict setObject:@(type) forKey:@"type"];
            PCDDropModel *model = [PCDDropModel dropMenuWithDictonary:tempDict];
            [self.titleImageArrM addObject:model];
        }
        
        [kWindow addSubview:self.cover];
        UITapGestureRecognizer *tapCover = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCoverClick)];
        [self.cover addGestureRecognizer:tapCover];
        
        self.backgroundColor = [UIColor clearColor];
        [kWindow addSubview:self];
        
        [self addSubview:self.tableView];
    }
    return self;
}


- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 8, self.frame.size.width, self.frame.size.height - 8) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.scrollEnabled = NO;
        _tableView.layer.masksToBounds = YES;
        _tableView.layer.cornerRadius = 6.f;
//        _tableView.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:255 / 255.0 blue:255 / 255.0 alpha:1];
        _tableView.backgroundColor = [UIColor clearColor];

    }
    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titleImageArrM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PCDDropCell *cell = [PCDDropCell dropMenuCellWithTableView:tableView];
    cell.model = self.titleImageArrM[indexPath.row];
    float r = [self.RGBStrValueArr[0] floatValue] / 255.0;
    float g = [self.RGBStrValueArr[1] floatValue] / 255.0;
    float b = [self.RGBStrValueArr[2] floatValue] / 255.0;
    CGFloat alpha = self.opacity?self.opacity:1;
    cell.backgroundColor = [UIColor colorWithRed:r green:g blue:b alpha:alpha];
    cell.titleL.textColor = _titleColor;
    cell.line.backgroundColor = _lineColor;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	if ([self selectHandler]) {
		[self selectHandler](indexPath.row);
	}
    [self removeDropView];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return _rowHeight;
}

- (UIView *)cover {
    if (!_cover) {
        _cover = [[UIView alloc] initWithFrame:kWindow.bounds];
//        _cover.backgroundColor = [UIColor blackColor];
//        _cover.alpha = 0.1;
        _cover.backgroundColor = [UIColor clearColor];
    }
    return _cover;
}

#pragma mark - cover tapAction
- (void)tapCoverClick {
  
    [self removeDropView];
}

#pragma mark - remove cover
- (void)removeDropView {
    [self.tableView removeFromSuperview];
    [self.cover removeFromSuperview];
    [self removeFromSuperview];
}

- (void)drawRect:(CGRect)rect {
	
    CGContextRef context = UIGraphicsGetCurrentContext();
    /*画三角形*/
    CGPoint sPoints[3];//坐标点
    sPoints[0] = CGPointMake(_arrowOffset, 0);//坐标1
    sPoints[1] = CGPointMake(_arrowOffset - 8, 8);//坐标2
    sPoints[2] = CGPointMake(_arrowOffset + 8, 8);//坐标3
    CGContextAddLines(context, sPoints, 3);//添加线
    //填充色
    float r = [self.RGBStrValueArr[0] floatValue] / 255.0;
    float g = [self.RGBStrValueArr[1] floatValue] / 255.0;
    float b = [self.RGBStrValueArr[2] floatValue] / 255.0;
    
    CGFloat alpha = self.opacity?self.opacity:1;
    UIColor *aColor = [UIColor colorWithRed:r green:g blue:b alpha:alpha];
    CGContextSetFillColorWithColor(context, aColor.CGColor);
    CGContextSetRGBStrokeColor(context,r, g, b,0);//画笔线的颜色 边框整透明
    CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathFillStroke); //根据坐标绘制路径
}

//将UIColor转换为RGB值
- (NSMutableArray *)changeUIColorToRGB:(UIColor *)color
{
    NSMutableArray *RGBStrValueArr = [[NSMutableArray alloc] init];
    NSString *RGBStr = nil;
    //获得RGB值描述
    NSString *RGBValue = [NSString stringWithFormat:@"%@",color];
    //将RGB值描述分隔成字符串
    NSArray *RGBArr = [RGBValue componentsSeparatedByString:@" "];
    //获取红色值
    int r = [[RGBArr objectAtIndex:1] intValue] * 255;
    RGBStr = [NSString stringWithFormat:@"%d",r];
    [RGBStrValueArr addObject:RGBStr];
    //获取绿色值
    int g = [[RGBArr objectAtIndex:2] intValue] * 255;
    RGBStr = [NSString stringWithFormat:@"%d",g];
    [RGBStrValueArr addObject:RGBStr];
    //获取蓝色值
    int b = [[RGBArr objectAtIndex:3] intValue] * 255;
    RGBStr = [NSString stringWithFormat:@"%d",b];
    [RGBStrValueArr addObject:RGBStr];
    //返回保存RGB值的数组
    return RGBStrValueArr;
}

//16进制颜色(html颜色值)字符串转为UIColor
- (NSMutableArray *)hexStringToColor:(NSString *)stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [NSMutableArray arrayWithObjects:@(r),@(g),@(b), nil];
}

#pragma mark - 箭头x偏移值
- (void)setArrowOffset:(CGFloat)arrowOffset {
  
    _arrowOffset = arrowOffset;
    [self setNeedsDisplay];
}
#pragma mark - 类型
- (void)setType:(PCDDropType)type {
  
  _type = type;
  for (PCDDropModel *model in self.titleImageArrM) {
    model.type = type;
  }
  [self.tableView reloadData];
}

#pragma mark - 箭头颜色
- (void)setArrowColor:(UIColor *)arrowColor {
  
    _arrowColor = arrowColor;
    self.RGBStrValueArr = [self changeUIColorToRGB:arrowColor];
    [self setNeedsDisplay];
}

- (void)setArrowColor16:(NSString *)arrowColor16 {
    _arrowColor16 = arrowColor16;
    self.RGBStrValueArr = [self hexStringToColor:arrowColor16];
    [self setNeedsDisplay];
}

#pragma mark - 文字颜色
- (void)setTitleColor:(UIColor *)titleColor {
  
    _titleColor = titleColor;
    [self.tableView reloadData];
}

#pragma mark - 线条颜色
- (void)setLineColor:(UIColor *)lineColor {
  
    _lineColor = lineColor;
    [self.tableView reloadData];
}

@end

@interface PCDDropCell()

@property (nonatomic, assign) CGFloat screenCenter;
@end

@implementation PCDDropCell

+ (instancetype)dropMenuCellWithTableView:(UITableView *)tableView {
    PCDDropCell *cell = [tableView dequeueReusableCellWithIdentifier:kDropMenuCellID];
    if (!cell) {
        cell = [[PCDDropCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kDropMenuCellID];
    }
    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
	
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.imageIV = [[UIImageView alloc] init];
        [self.contentView addSubview:self.imageIV];
        
        self.titleL = [[UILabel alloc] init];
        self.titleL.textColor = [UIColor blackColor];
        self.titleL.font = [UIFont systemFontOfSize:15.f];
        [self.contentView addSubview:self.titleL];
        
        self.line = [[UIImageView alloc] init];
        self.line.backgroundColor = [UIColor lightGrayColor];
        [self.contentView addSubview:self.line];
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.screenCenter = self.contentView.frame.size.height * 0.5;
    
    self.imageIV.frame = CGRectMake(10, self.screenCenter - 8, 16, 16);
    if (self.model.type == PCDDropTypeTitle) {
        self.titleL.frame = CGRectMake(10, self.screenCenter - 10, self.frame.size.width-20, 20);
        self.titleL.textAlignment = NSTextAlignmentCenter;
    } else {
        self.titleL.frame = CGRectMake(CGRectGetMaxX(self.imageIV.frame) + 10, self.screenCenter - 10, self.contentView.frame.size.width - 50, 20);
    }
    self.line.frame = CGRectMake(0, self.contentView.frame.size.height - 0.5, self.contentView.frame.size.width, 0.5);
}

- (void)setModel:(PCDDropModel *)model {
    _model = model;
    if (model.type == PCDDropTypeTitle) {
        self.titleL.frame = CGRectMake(10, self.screenCenter - 10, self.frame.size.width, 20);
    } else {
        self.imageIV.image = [UIImage imageNamed:model.image];
    }
    self.titleL.textColor = [UIColor blackColor];
    self.line.backgroundColor = [UIColor lightGrayColor];

    self.titleL.text = model.title;
}

@end

@interface PCDDropModel()
@end

@implementation PCDDropModel

- (instancetype)initWithDictonary:(NSDictionary *)dict {
	
    if (self = [super init]) {
		
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

+ (instancetype)dropMenuWithDictonary:(NSDictionary *)dict {
	
    return [[self alloc] initWithDictonary:dict];
}

@end

